from flask import (
    Blueprint, 
    request, 
    session, 
    redirect, 
    url_for, 
    render_template, 
    flash,
    current_app
)
import bcrypt
from functools import wraps
import datetime
import socket
import json
import os

auth_bp = Blueprint('auth', __name__)

# 默认管理员密码（建议首次登录后立即修改）
DEFAULT_PASSWORD = "admin123"
PASSWORD_HASH = bcrypt.hashpw(DEFAULT_PASSWORD.encode('utf-8'), bcrypt.gensalt())

def get_client_ip():
    """获取客户端IP地址"""
    if request.environ.get('HTTP_X_FORWARDED_FOR'):
        ip = request.environ['HTTP_X_FORWARDED_FOR'].split(',')[0]
    else:
        ip = request.environ.get('REMOTE_ADDR', 'unknown')
    try:
        hostname = socket.gethostbyaddr(ip)[0]
    except:
        hostname = 'unknown'
    return {'ip': ip, 'hostname': hostname}

def save_login_record(ip_info, success=True):
    """保存登录记录"""
    log_dir = os.path.join(current_app.root_path, '..', 'logs')
    log_file = os.path.join(log_dir, 'login_records.json')
    
    record = {
        'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'ip': ip_info['ip'],
        'hostname': ip_info['hostname'],
        'success': success
    }
    
    try:
        if os.path.exists(log_file):
            with open(log_file, 'r', encoding='utf-8') as f:
                records = json.load(f)
        else:
            records = []
        
        records.append(record)
        
        # 只保留最近100条记录
        if len(records) > 100:
            records = records[-100:]
            
        with open(log_file, 'w', encoding='utf-8') as f:
            json.dump(records, f, ensure_ascii=False, indent=2)
    except Exception as e:
        print(f"Error saving login record: {e}")

@auth_bp.route('/')
def index():
    if session.get('logged_in'):
        return redirect(url_for('download.index'))
    return redirect(url_for('auth.login'))

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('logged_in'):
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function

@auth_bp.route('/auth/login', methods=['GET', 'POST'])
def login():
    if session.get('logged_in'):
        return redirect(url_for('download.index'))
    
    if request.method == 'POST':
        password = request.form.get('password', '')
        ip_info = get_client_ip()
        
        if bcrypt.checkpw(password.encode('utf-8'), PASSWORD_HASH):
            session['logged_in'] = True
            session['login_ip'] = ip_info['ip']
            session['login_hostname'] = ip_info['hostname']
            session['login_time'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            save_login_record(ip_info, success=True)
            return redirect(url_for('download.index'))
        
        save_login_record(ip_info, success=False)
        flash('密码错误')
    return render_template('login.html')

@auth_bp.route('/auth/logout')
def logout():
    session.pop('logged_in', None)
    session.pop('login_ip', None)
    session.pop('login_hostname', None)
    session.pop('login_time', None)
    return redirect(url_for('auth.login'))

@auth_bp.route('/auth/change_password', methods=['POST'])
@login_required
def change_password():
    global PASSWORD_HASH
    old_password = request.form.get('old_password', '')
    new_password = request.form.get('new_password', '')
    
    if not bcrypt.checkpw(old_password.encode('utf-8'), PASSWORD_HASH):
        return {'success': False, 'message': '原密码错误'}, 400
        
    PASSWORD_HASH = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
    return {'success': True, 'message': '密码修改成功'}

@auth_bp.route('/auth/login_records')
@login_required
def get_login_records():
    """获取登录记录"""
    log_file = os.path.join(current_app.root_path, '..', 'logs', 'login_records.json')
    try:
        if os.path.exists(log_file):
            with open(log_file, 'r', encoding='utf-8') as f:
                records = json.load(f)
            return {'success': True, 'records': records}
    except Exception as e:
        print(f"Error reading login records: {e}")
    return {'success': False, 'records': []}

# 确保 auth_bp 可以被导入
__all__ = ['auth_bp'] 